import json
import time
import uuid
import base64
import random
import datetime
import urllib.parse
from chinese_calendar import is_workday
from django.shortcuts import HttpResponse
from django.core import serializers
import rest_framework
from rest_framework.views import APIView
from rest_framework.response import Response
from django.db.models import Q
from rest_framework import mixins, viewsets, status
from rest_framework.permissions import IsAuthenticated
from rest_framework.authentication import SessionAuthentication
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from django_filters.rest_framework import DjangoFilterBackend
from apps.user_operation.permissions import IsOwner
from apps.supply_order.utils import UntilPagination
from rest_framework import filters

from apps.coffee.utils import distance_sorted_v2
from core.tools.FormatXmlArray import FormatXmlArray
from core.wchat.mini_base import aes_cipher
from core.wchat.models import RefundRecord as WxRefundRecord
from . import models as my_models
from . import serializers as my_serializers
from . import filters as my_filters
from .client import CoffeeApi
from apps.supply_order.models import RefundRecord
from core.wchat.wx_base import mc
from django.contrib.auth import get_user_model

User = get_user_model()


# banner
class BannerViewSets(mixins.ListModelMixin, viewsets.GenericViewSet):
    queryset = my_models.Banner.objects.all()
    serializer_class = my_serializers.BannerSerializers


# 分类
class TradeViewSets(mixins.ListModelMixin, viewsets.GenericViewSet):
    serializer_class = my_serializers.TradeSerializers
    queryset = my_models.Trade.objects.filter(is_show=True)


# 咖啡机列表
class ClientViewSets(mixins.ListModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet):
    serializer_class = my_serializers.CoffeeClientSerializers
    queryset = my_models.CoffeeClient.objects.filter(status=True)
    pagination_class = UntilPagination
    filter_backends = (DjangoFilterBackend, filters.SearchFilter)
    filter_class = my_filters.ClientFilter

    def get_queryset(self):
        return my_models.CoffeeClient.objects.filter(status=True)

    # from core.tools.func_utils import geodistance
    def list(self, request, *args, **kwargs):
        # super(ClientViewSets, self).list(request, *args, **kwargs)
        # queryset = self.filter_queryset(self.get_queryset())
        queryset = my_models.CoffeeClient.objects.filter(status=True, sort_level=0)
        lon = request.query_params.get("lon")
        lat = request.query_params.get("lat")
        top_queryset = my_models.CoffeeClient.objects.filter(status=True, sort_level__gt=0).order_by("-sort_level")
        top_serializer = self.get_serializer(top_queryset, many=True)
        if lon and lat and lon != "undefined" and lat != "undefined":
            serializer = self.get_serializer(queryset, many=True)
            queryset = distance_sorted_v2(serializer.data, lon, lat, top_serializer.data)
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)
        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)


# 优惠券列表
class CouponViewSets(mixins.ListModelMixin, viewsets.GenericViewSet):
    """
    自己拥有的优惠券列表（并且正常可以使用）
    已过期的优惠券列表
    """
    serializer_class = my_serializers.CouponSerializers
    pagination_class = UntilPagination
    permission_classes = (IsAuthenticated,)
    authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)
    filter_backends = (DjangoFilterBackend, filters.SearchFilter)
    filter_class = my_filters.CouponInfoFilter

    def get_queryset(self):
        queryset = my_models.CouponInfo.objects.filter(
            user=self.request.user, given=False,
            c_type__in=my_models.CouponInfo.show_c_type_list
        ).order_by(
            "expire_time")
        return queryset

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        queryset = my_models.CouponInfo.objects.group_by(queryset)
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)


# 提交订单时展示优惠券列表/优惠券统计
class OrdersCouponViewSets(mixins.ListModelMixin, viewsets.GenericViewSet):
    """
    自己拥有的优惠券列表（并且正常可以使用）
    已过期的优惠券列表
    """
    serializer_class = my_serializers.CouponSerializers
    permission_classes = (IsAuthenticated,)
    authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)
    filter_backends = (DjangoFilterBackend, filters.SearchFilter)
    filter_class = my_filters.CouponSourceFilter

    def get_queryset(self):
        queryset = my_models.CouponInfo.objects.can_use_coupon(self.request.user)
        return queryset

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        queryset = my_models.CouponInfo.objects.group_by_type_and_quota(queryset)
        if request.query_params.get("source") == 2 or request.query_params.get("source") == "2":
            queryset = my_models.CouponInfo.objects.group_by_counts(queryset)
        else:
            queryset = my_models.CouponInfo.objects.group_by_type_and_quota(queryset)
        # page = self.paginate_queryset(queryset)
        # if page is not None:
        #     if request.query_params.get("source") == 2 or request.query_params.get("source") == "2":
        #         serializer = self.get_serializer(page, many=True, fields=("counts", "c_type"))
        #     else:
        #         serializer = self.get_serializer(page, many=True, fields=("counts", "c_type", "quota"))
        #     return self.get_paginated_response(serializer.data)
        if request.query_params.get("source") == 2 or request.query_params.get("source") == "2":
            serializer = self.get_serializer(queryset, many=True, fields=("counts", "c_type"))
        else:
            serializer = self.get_serializer(queryset, many=True, fields=("counts", "c_type", "quota"))
        data_list = []
        for i in my_models.CouponInfo.show_c_type_list:
            for data in serializer.data:
                if data.get("c_type") == i:
                    data_list.append(data)
        print("data_list", data_list)
        if data_list:
            key = f"c_type_{self.request.user.id}"
            result = data_list[0].get("c_type")
            print(result)
            mc.set(key, result, 60 * 30)
        return Response(data_list)


# 使用记录
class UseViewSets(mixins.ListModelMixin, viewsets.GenericViewSet):
    """
    已使用的优惠券列表
    """
    serializer_class = my_serializers.UseSerializers
    pagination_class = UntilPagination
    permission_classes = (IsAuthenticated,)
    authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)
    filter_backends = (DjangoFilterBackend, filters.SearchFilter)
    filter_class = my_filters.UseFilter

    def get_queryset(self):
        queryset = my_models.UseRecord.objects.filter(user=self.request.user)
        return queryset


# 转增记录
class GiveRecordViewSets(mixins.ListModelMixin, mixins.UpdateModelMixin, viewsets.GenericViewSet):
    """
    list:转增记录列表
    """
    pagination_class = UntilPagination
    permission_classes = (IsAuthenticated,)
    authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)
    filter_backends = (DjangoFilterBackend, filters.SearchFilter)
    filter_class = my_filters.GiveRecordFilter

    def get_serializer_class(self):
        if self.action == "update":
            return my_serializers.CancelGiveRecordSerializers
        else:
            return my_serializers.GiveRecordSerializers

    def get_queryset(self):
        queryset = my_models.GiveRecord.objects.filter(
            Q(receive_user=self.request.user) | Q(own_user=self.request.user))
        return queryset


# 订单管理, 提交订单>>发起支付(立刻购买)
class Orders(mixins.CreateModelMixin, mixins.ListModelMixin, mixins.UpdateModelMixin, mixins.RetrieveModelMixin,
             viewsets.GenericViewSet):
    permission_classes = (IsAuthenticated, IsOwner)
    authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)
    filter_backends = (DjangoFilterBackend, filters.SearchFilter)
    filter_class = my_filters.OrdersFilter
    pagination_class = UntilPagination
    lookup_field = "orderNo"

    def get_queryset(self):
        queryset = my_models.CoffeeOrder.objects.filter(user=self.request.user)
        return queryset

    def get_serializer_class(self):
        if self.action == "create":
            return my_serializers.CreateOrdersSerializers
        elif self.action == "list":
            return my_serializers.OrderSerializers
        elif self.action == "retrieve":
            return my_serializers.OrderSerializers
        else:
            return my_serializers.UpdateOrdersSerializers

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        print(request.data, "request.data")
        serializer.is_valid(raise_exception=True)
        instance = self.perform_create(serializer)
        # orderNo 咖啡订单
        context = {"id": instance.id, "orderNo": instance.orderNo, "result": instance.result}
        payment = instance.payment
        cash = instance.cash
        total_fee = instance.total_fee
        if payment < cash:
            context["show"] = False
        else:
            context["show"] = True
        context["total_fee"] = total_fee
        context["notifyUrl"] = "https://c2c.kalaibao.com/shop/api/payment_notice"
        return Response(context, status=status.HTTP_201_CREATED, headers=context)

    def perform_create(self, serializer):
        return serializer.save()


class OrderUpdateViewSets(mixins.CreateModelMixin, viewsets.GenericViewSet):
    serializer_class = my_serializers.OrderUpdateSerializers
    permission_classes = (IsAuthenticated, IsOwner)
    authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)
    # lookup_field = "orderNo"
    # queryset = my_models.CoffeeOrder.objects.all()

    def perform_create(self, serializer):
        return serializer.save()

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        instance = self.perform_create(serializer)
        context = {"id": instance.id, "orderNo": instance.orderNo, "result": instance.result}
        return Response(context)


# 通过手机号赠送  优惠券转增
class GiveByMobile(mixins.CreateModelMixin, viewsets.GenericViewSet):
    permission_classes = (IsAuthenticated,)
    authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)
    serializer_class = my_serializers.GiveByTelSerializers


# 通过二维码地址赠送   优惠券转增
class GiveRecordUrl(mixins.CreateModelMixin, viewsets.GenericViewSet):
    permission_classes = (IsAuthenticated,)
    authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)
    serializer_class = my_serializers.GiveRecordUrlSerializers

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        params = self.perform_create(serializer)
        type_source = serializer.validated_data["type_source"]
        page = serializer.validated_data["page"]
        params = json.dumps(params)
        key = uuid.uuid1().hex
        mc.set(key, params, 3600 * 24 * 7)
        print(key, "key")
        print(page, "page")
        if type_source == "wchatMini":
            from core.wchat.mini_base import wechat_client
            response = wechat_client.wxa.get_wxa_code_unlimited(key, page=page)
            content = b"data:image/png;base64," + base64.b64encode(response.content)
        else:
            # 普通二维码
            # from core.tools.edit_photo import EditPicture
            # url = page + "?scene=" + key
            # image_stream, buf = EditPicture.make_qr_code(url)

            # 关注二维码
            from core.wchat.wx_base import WxBase
            wx_base = WxBase()
            content = json.dumps({"IMCoffee": key})
            image_stream = wx_base.get_qr_response(content, short=False)
            content = b"data:image/png;base64," + base64.b64encode(image_stream)
        return Response({"image": content}, status=status.HTTP_201_CREATED)

    def perform_create(self, serializer):
        return serializer.save()


class GiveRecordUrlV2(mixins.CreateModelMixin, viewsets.GenericViewSet):
    permission_classes = (IsAuthenticated,)
    authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)
    serializer_class = my_serializers.GiveRecordUrlSerializers

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        params = self.perform_create(serializer)
        type_source = serializer.validated_data["type_source"]
        page = serializer.validated_data["page"]
        params = json.dumps(params)
        key = uuid.uuid1().hex
        mc.set(key, params, 3600 * 24 * 7)
        print(key, "key")
        print(page, "page")
        if type_source == "wchatMini":
            from core.wchat.mini_base import wechat_client_howhow
            response = wechat_client_howhow.wxa.get_wxa_code_unlimited(key, page=page)
            content = b"data:image/png;base64," + base64.b64encode(response.content)
        else:
            # 普通二维码
            # from core.tools.edit_photo import EditPicture
            # url = page + "?scene=" + key
            # image_stream, buf = EditPicture.make_qr_code(url)

            # 关注二维码
            from core.wchat.wx_base import WxBase
            wx_base = WxBase()
            content = json.dumps({"IMCoffee": key})
            image_stream = wx_base.get_qr_response(content, short=False)
            content = b"data:image/png;base64," + base64.b64encode(image_stream)
        return Response({"image": content}, status=status.HTTP_201_CREATED)

    def perform_create(self, serializer):
        return serializer.save()


# 通过扫码领取
class ReceiveViewSets(mixins.CreateModelMixin, viewsets.GenericViewSet):
    permission_classes = (IsAuthenticated,)
    authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)
    serializer_class = my_serializers.ReceiveSerializers

    def create(self, request, *args, **kwargs):
        print(f"ReceiveViewSets data {json.dumps(request.data)}")
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        instance = self.perform_create(serializer)
        coupon_id_list = instance.get("coupon_id_list")
        coupon_queryset = my_models.CouponInfo.objects.filter(id__in=coupon_id_list)
        receive_list = my_models.CouponInfo.objects.group_by_type_and_quota(coupon_queryset)
        data = my_serializers.CouponSerializers(receive_list, many=True,
                                                fields=("c_type", "counts", "quota", "name")).data
        return HttpResponse(data, status=status.HTTP_201_CREATED)

    def perform_create(self, serializer):
        return serializer.save()


# 商品信息
class GoodsViewSets(mixins.RetrieveModelMixin, mixins.ListModelMixin, viewsets.GenericViewSet):
    serializer_class = my_serializers.GoodsSerializers
    lookup_field = "pid"
    queryset = my_models.Coffee.objects.filter(show=True)


# 咖啡制作成功后回调
class CoffeeNoticeView(APIView):
    def get(self, request, *args, **kwargs):
        print(self.request.data, "data get")
        print(self.request.query_params, "query_params get")
        print(self.request.query_params, "query_params")
        ID = self.request.query_params.get("ID")
        PID = self.request.query_params.get("PID")
        VMC = self.request.query_params.get("VMC")
        MAC = self.request.query_params.get("MAC")
        if CoffeeApi(ID, VMC, PID).verify(MAC):
            instance = my_models.CoffeeOrder.objects.get(orderNo=ID)
            instance.update_coffee_make_result(1)
            return Response(status=status.HTTP_200_OK)
        else:
            return HttpResponse(status=status.HTTP_400_BAD_REQUEST)
            # return HttpResponse(status=status.HTTP_400_BAD_REQUEST)

    def post(self, request, *args, **kwargs):
        print(self.request.data, "data post")
        print(self.request.query_params, "query_params post")
        ID = self.request.query_params.get("ID")
        PID = self.request.query_params.get("PID")
        VMC = self.request.query_params.get("VMC")
        MAC = self.request.query_params.get("MAC")
        if CoffeeApi(ID, VMC, PID).verify(MAC):
            instance = my_models.CoffeeOrder.objects.get(orderNo=ID)
            instance.update_coffee_make_result(1)
            return Response(status=status.HTTP_200_OK)
        else:
            return HttpResponse(status=status.HTTP_400_BAD_REQUEST)
            # return HttpResponse(status=status.HTTP_400_BAD_REQUEST)


class ScanCodeResult(mixins.ListModelMixin, viewsets.GenericViewSet):
    # permission_classes = (IsAuthenticated,)
    # authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)

    def list(self, request, *args, **kwargs):
        from core.wchat.wx_base import mc
        key = self.request.query_params.get("key")
        print("ScanCodeResult key", key)
        if mc.get(key):
            data = json.loads(mc.get(key))
            print("ScanCodeResult: ", data)
            channel_key = data.get("channel_key")
            # channel_object = my_models.Channel.objects.get(key=channel_key)
            if data.get("share_user"):
                # 好友转增
                return Response(json.loads(mc.get(key)))
            elif data.get("give_record_list"):
                # 系统赠送
                give_record_obj = data.get("give_record_list")[0]
            else:
                # 订单
                return Response(json.loads(mc.get(key)))

            c_type = int(give_record_obj.get("c_type"))
            # num = channel_object.num
            num = give_record_obj.get("num")
            own_user = User.objects.get(mobile=channel_key)
            if c_type == 2:  # 如果是立减券面额越大越靠前
                queryset = my_models.CouponInfo.objects.filter(
                    c_type=c_type, user=own_user, used=False, expired=False).order_by("-quota", "expire_time")
            elif c_type == 9:  # 如果是兑换券面额越大越靠前
                queryset = my_models.CouponInfo.objects.filter(
                    c_type=c_type, user=own_user, used=False, expired=False).order_by("quota", 'expire_time')
            else:
                queryset = my_models.CouponInfo.objects.filter(
                    c_type=c_type, user=own_user, used=False, expired=False).order_by("expire_time")

            instance = queryset.first()
            if not instance:
                return Response({"message": "券已经发完了"}, status=400)
            quota = instance.quota / 100.0
            response = {"quota": quota, "num": num, "c_type": c_type}
            return Response(response, headers=response)

        else:
            content = {
                "key": [
                    "数据已过期"
                ]
            }
            return Response(content, status=status.HTTP_400_BAD_REQUEST)


class ChannelCouponViewSets(mixins.ListModelMixin, viewsets.GenericViewSet):
    """
    自己拥有的优惠券列表（并且正常可以使用）
    已过期的优惠券列表
    """
    serializer_class = my_serializers.CouponSerializers
    filter_backends = (DjangoFilterBackend, filters.SearchFilter)

    def get_queryset(self):
        key = self.request.query_params.get("key")
        user = User.objects.get(mobile=key)
        queryset = my_models.CouponInfo.objects.can_use_coupon(user)
        return queryset

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        queryset = my_models.CouponInfo.objects.group_by_type_and_quota(queryset)
        if request.query_params.get("source") == 2 or request.query_params.get("source") == "2":
            queryset = my_models.CouponInfo.objects.group_by_counts(queryset)
        else:
            queryset = my_models.CouponInfo.objects.group_by_type_and_quota(queryset)
        # page = self.paginate_queryset(queryset)
        # if page is not None:
        #     if request.query_params.get("source") == 2 or request.query_params.get("source") == "2":
        #         serializer = self.get_serializer(page, many=True, fields=("counts", "c_type"))
        #     else:
        #         serializer = self.get_serializer(page, many=True, fields=("counts", "c_type", "quota"))
        #     return self.get_paginated_response(serializer.data)
        if request.query_params.get("source") == 2 or request.query_params.get("source") == "2":
            serializer = self.get_serializer(queryset, many=True, fields=("counts", "c_type"))
        else:
            serializer = self.get_serializer(queryset, many=True, fields=("counts", "c_type", "quota"))
        data_list = []
        for i in [7, 9, 2]:
            for data in serializer.data:
                if data.get("c_type") == i:
                    data_list.append(data)
        return Response(data_list)


# 通过扫码系统赠送
class SystemReceiveViewSets(mixins.CreateModelMixin, viewsets.GenericViewSet):
    permission_classes = (IsAuthenticated,)
    authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)
    serializer_class = my_serializers.SystemReceiveSerializers

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        coupon_id_list = self.perform_create(serializer)
        coupon_queryset = my_models.CouponInfo.objects.filter(id__in=coupon_id_list)
        receive_list = my_models.CouponInfo.objects.group_by_type_and_quota(coupon_queryset)
        data = my_serializers.CouponSerializers(receive_list, many=True, fields=("c_type", "counts", "quota")).data
        print(data, "SystemReceiveViewSets")
        return HttpResponse(data, status=status.HTTP_201_CREATED)

    def perform_create(self, serializer):
        return serializer.save()


# 通过扫固定码 盲盒优惠券
class SystemCodeRandomViewSets(mixins.CreateModelMixin, viewsets.GenericViewSet):
    permission_classes = (IsAuthenticated,)
    authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)
    serializer_class = my_serializers.CreateRandomCouponShopSerializers

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        obj = self.perform_create(serializer)
        data = my_serializers.CouponSerializers(obj, many=False, fields=("c_type", "quota", "name")).data
        data = {"coupon": {"name": data.get("name"), "c_type": data.get("c_type"), "quota": data.get("quota")},
                "share_id": ""}
        headers = self.get_success_headers(data)
        return Response(data, status=status.HTTP_201_CREATED, headers=headers)

    def perform_create(self, serializer):
        return serializer.save()


# 获取小程序码(H5提交订单)
class H5CommitOrderViewSets(mixins.CreateModelMixin, viewsets.GenericViewSet):
    serializer_class = my_serializers.H5CommitOrderSerializers

    def perform_create(self, serializer):
        return serializer.save()

    def create(self, request, *args, **kwargs):
        from core.wchat.mini_base import wechat_client
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        key = self.perform_create(serializer)
        page = self.request.data.get("page")
        response = wechat_client.wxa.get_wxa_code_unlimited(key, page=page)
        content = b"data:image/png;base64," + base64.b64encode(response.content)
        return Response({"image": content, "key": key})


class V2H5CommitOrderViewSets(mixins.CreateModelMixin, viewsets.GenericViewSet):
    serializer_class = my_serializers.H5CommitOrderSerializers

    def perform_create(self, serializer):
        return serializer.save()

    def create(self, request, *args, **kwargs):
        from core.wchat.mini_base import wechat_client_howhow
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        key = self.perform_create(serializer)
        page = self.request.data.get("page")
        response = wechat_client_howhow.wxa.get_wxa_code_unlimited(key, page=page)
        content = b"data:image/png;base64," + base64.b64encode(response.content)
        return Response({"image": content, "key": key})


class KeyValue(APIView):
    def get(self, request, *args, **kwargs):
        key = self.request.query_params.get("key")
        from core.wchat.wx_base import mc
        if mc.get(key):
            return Response(json.loads(mc.get(key)))
        else:
            content = {
                "key": [
                    "数据已过期"
                ]
            }
            return Response(content, status=status.HTTP_400_BAD_REQUEST)


# 微信退款回调通知（coffee）
def refund_coffee(request):
    if request.method == "POST":
        body = request.body
        refund_dict = FormatXmlArray.xml_to_array(body)
        print(refund_dict, "refund_dict result")
        req_info = aes_cipher.decrypt(refund_dict.get("req_info"))
        req_dict = FormatXmlArray.xml_to_array(req_info)
        print(req_dict, "req_info")
        # 更新退款订单
        wx_refund_instance = WxRefundRecord.objects.get(out_refund_no=req_dict.get("out_refund_no"))
        # 更新微信退款
        wx_refund_instance.update_req_info(req_dict)
        if req_dict.get("refund_status") == "SUCCESS":
            coffee_order = my_models.CoffeeOrder.objects.get(out_trade_no=req_dict.get("out_trade_no"))
            # 创建退款记录
            data = dict()
            data["refund_fee"] = req_dict.get("refund_fee")
            data["refund_type"] = coffee_order.pay_type
            data["out_refund_no"] = req_dict.get("out_refund_no")
            refund_instance = RefundRecord.objects.create_refund(**data)
            # 退券
            coffee_order.refund_coupon(result=2, refund=refund_instance)
            re = {"return_code": "SUCCESS", "return_msg": "OK"}
        else:
            re = {"return_code": "ERROR", "return_msg": "ERROR"}
        re = FormatXmlArray.array_to_xml(re)
        return HttpResponse(re)
    else:
        return HttpResponse("hello world")


class CouponTypeList(APIView):
    def get(self, request, *args, **kwargs):
        data = list(my_models.CouponInfo.cType)
        new_data = []
        for i in data:
            if i[0] == 0:
                new_data.append({"id": i[0], "name": "全部"})
            if i[0] in my_models.CouponInfo.show_c_type_list:
                new_data.append({"id": i[0], "name": i[1]})
        return Response(new_data)


# -----------------------------------------卡包--------------------------------------
# 优惠券列表
class CardBagViewSets(mixins.ListModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet):
    """
    自己拥有的优惠券列表（并且正常可以使用）
    已过期的优惠券列表
    """
    serializer_class = my_serializers.CardBagSerializers
    pagination_class = UntilPagination

    def get_queryset(self):
        queryset = my_models.CardBag.objects.filter(can_sales=True).order_by(
            "ordering")
        return queryset


# 订单购买
class CardBagOrdersViewSets(mixins.ListModelMixin, mixins.RetrieveModelMixin, mixins.CreateModelMixin,
                            mixins.UpdateModelMixin,
                            viewsets.GenericViewSet):
    pagination_class = UntilPagination
    permission_classes = (IsAuthenticated,)
    authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)
    filter_backends = (DjangoFilterBackend, filters.SearchFilter)
    filter_class = my_filters.CardBagOrdersFilter

    def get_queryset(self):
        return my_models.CardBagOrders.objects.filter(user=self.request.user)

    def get_serializer_class(self):
        if self.action == "update":
            return my_serializers.RefundCardBagOrdersSerializers
        else:
            return my_serializers.CardBagOrdersSerializers


class CardBagOrdersViewSetsV2(mixins.ListModelMixin, mixins.RetrieveModelMixin, mixins.CreateModelMixin,
                              mixins.UpdateModelMixin,
                              viewsets.GenericViewSet):
    pagination_class = UntilPagination
    permission_classes = (IsAuthenticated,)
    authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)
    filter_backends = (DjangoFilterBackend, filters.SearchFilter)
    filter_class = my_filters.CardBagOrdersFilter

    def get_queryset(self):
        return my_models.CardBagOrders.objects.filter(user=self.request.user)

    def get_serializer_class(self):
        if self.action == "update":
            return my_serializers.RefundCardBagOrdersSerializersV2
        else:
            return my_serializers.CardBagOrdersSerializers


# 购物车
class ShopCarViewSets(mixins.ListModelMixin, mixins.RetrieveModelMixin, mixins.CreateModelMixin,
                      viewsets.GenericViewSet):
    pagination_class = UntilPagination
    permission_classes = (IsAuthenticated, IsOwner)
    authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)

    def get_serializer_class(self):
        if self.action == "create":
            return my_serializers.ShopCarSerializers
        elif self.action == "list":
            return my_serializers.ShopCarListSerializers
        else:
            return my_serializers.ShopCarUpdateSerializers

    def get_queryset(self):
        return my_models.ShopCar.objects.filter(user_id=self.request.user.id, status=True)


# 微信退款回调通知（卡包）
def refund_card_bag(request):
    if request.method == "POST":
        body = request.body
        refund_dict = FormatXmlArray.xml_to_array(body)
        print(refund_dict, "refund_dict result")
        req_info = aes_cipher.decrypt(refund_dict.get("req_info"))
        req_dict = FormatXmlArray.xml_to_array(req_info)
        print(req_dict, "req_info")
        # 更新退款订单
        wx_refund_instance = WxRefundRecord.objects.get(out_refund_no=req_dict.get("out_refund_no"))
        # 更新微信退款
        wx_refund_instance.update_req_info(req_dict)
        if req_dict.get("refund_status") == "SUCCESS":
            card_bag_order_instance = my_models.CardBagOrders.objects.get(out_trade_no=req_dict.get("out_trade_no"))
            # 创建退款记录
            data = dict()
            data["refund_fee"] = req_dict.get("refund_fee")
            data["refund_type"] = card_bag_order_instance.pay_type
            data["out_refund_no"] = req_dict.get("out_refund_no")
            refund_instance = RefundRecord.objects.create_refund(**data)
            # 退券
            card_bag_order_instance.update_refund(result=2, refund=refund_instance)
            re = {"return_code": "SUCCESS", "return_msg": "OK"}
        else:
            re = {"return_code": "ERROR", "return_msg": "ERROR"}
        re = FormatXmlArray.array_to_xml(re)
        return HttpResponse(re)
    else:
        return HttpResponse("hello world")


# 随机券
class RandomCouponViewSets(viewsets.GenericViewSet, mixins.CreateModelMixin, mixins.UpdateModelMixin):
    permission_classes = (IsAuthenticated,)
    authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)
    queryset = my_models.RandomCouponRecord.objects.all()

    def get_serializer_class(self):
        if self.action == "update":
            return my_serializers.UpdateRandomCouponSerializers
        else:
            return my_serializers.RandomCouponSerializers


class ReduceMoneyEveryDayActiveViewSets(viewsets.GenericViewSet, mixins.CreateModelMixin, mixins.ListModelMixin):
    authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)
    permission_classes = (IsOwner, IsAuthenticated)
    serializer_class = my_serializers.ReduceMoneyEveryDayActiveSerializers

    def list(self, request, *args, **kwargs):
        user_id = self.request.user.id
        queryset = my_models.ReduceMoneyEveryDayActive.objects.filter(user_id=user_id)
        if queryset.exists():
            return Response({"status": "ok"})
        else:
            return Response({"status": "not found"}, status=status.HTTP_404_NOT_FOUND)


class SelfInfoViewSet(mixins.RetrieveModelMixin, viewsets.GenericViewSet):
    """
    个人信息：
    """
    authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)
    permission_classes = (IsOwner, IsAuthenticated)
    serializer_class = my_serializers.UserInfoSerializers

    def get_queryset(self):
        return my_models.User.objects.filter(id=self.request.user.id)


# -----------------------------------------银行兑换券--------------------------------------
# 兑换
class BankExchangeCodeViewSets(mixins.CreateModelMixin, mixins.ListModelMixin, viewsets.GenericViewSet):
    permission_classes = (IsAuthenticated,)
    authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)
    serializer_class = my_serializers.BankExchangeCodeSerializers
    pagination_class = UntilPagination

    def get_queryset(self):
        return my_models.BankExchangeCode.objects.filter(user_id=self.request.user.id)

    def get_serializer_class(self):
        if self.action == "create":
            return my_serializers.BankExchangeCodeSerializers
        else:
            return my_serializers.ExchangeCodeRecordSerializers

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        instance = self.perform_create(serializer)
        # headers = self.get_success_headers(serializer.data)
        data = {"num": instance.num, "type": instance.get_c_type_display()}
        return Response(data, status=status.HTTP_201_CREATED, headers=data)

    def perform_create(self, serializer):
        return serializer.save()


class UserShareViewSets(viewsets.GenericViewSet, mixins.CreateModelMixin):
    permission_classes = (IsAuthenticated,)
    authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)
    serializer_class = my_serializers.ShareSerializers


class ReceiveSharedViewSets(viewsets.GenericViewSet, mixins.CreateModelMixin):
    permission_classes = (IsAuthenticated,)
    authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)
    serializer_class = my_serializers.ReceiveSharedSerializers


# 用户选择咖啡后，减钱活动显示当前价格
class CoffeePriceViewSets(viewsets.GenericViewSet, mixins.ListModelMixin):
    permission_classes = (IsAuthenticated,)
    authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)

    def list(self, request, *args, **kwargs):
        user = self.request.user
        queryset = my_models.ReduceMoneyEveryDay.objects.get_last_data(user_id=user.id)
        if queryset.exists():
            today = datetime.date.today()
            instance = queryset.first()
            reduce_date = instance.reduce_date
            money = instance.money
            if today != reduce_date:
                return Response({"money": money})
            else:
                return Response({"money": 0})
        else:
            return Response({"money": 0})


class PaymentTypeViewSets(viewsets.GenericViewSet, mixins.ListModelMixin):
    permission_classes = (IsAuthenticated,)
    authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)

    filter_backends = (DjangoFilterBackend, filters.SearchFilter)
    filter_class = my_filters.CouponInfoFilter

    def get_queryset(self):
        queryset = my_models.CouponInfo.objects.can_use_coupon(self.request.user)
        c_type = self.request.query_params.get("c_type")
        if c_type == 1 or c_type == "1":
            can_use_coupon = []
            for i in my_models.CouponInfo.cType[1:]:
                if "B" not in i[1]:
                    can_use_coupon.append(i[0])
        elif c_type == 2 or c_type == "2":
            can_use_coupon = []
            for i in my_models.CouponInfo.cType[1:]:
                if "A" not in i[1]:
                    can_use_coupon.append(i[0])
        else:
            can_use_coupon = []
        queryset = queryset.filter(c_type__in=can_use_coupon)
        return queryset

    def list(self, request, *args, **kwargs):
        c_type = self.request.query_params.get("c_type")
        print(c_type, "c_type PaymentTypeViewSets")
        # 这里使用了c_type
        coupon_queryset = self.get_queryset()
        coupon_queryset = my_models.CouponInfo.objects.group_by_type_and_quota(coupon_queryset)

        # 新逻辑  这里没用c_type
        coupon_queryset = my_models.CouponInfo.objects.group_by_type_and_quota(
            my_models.CouponInfo.objects.can_use_coupon(self.request.user))
        coupon_c_type_list = [int(i.get("c_type")) for i in coupon_queryset]
        if 7 in coupon_c_type_list:
            default = 7
        elif 9 in coupon_c_type_list:
            default = 9
        elif 2 in coupon_c_type_list:
            default = 2
        elif 6 in coupon_c_type_list or 1 in coupon_c_type_list:
            default = -2
        else:
            default = 0
        money = 0

        # 旧逻辑 每天减一毛 兑换券等 如果需要直接打开注释就行
        # level_free = [7]
        # level_exchange = [3, 8]
        # level_reduction = [2]
        # default = 0
        #
        reduce_active = 0  # 未报名
        #
        # # 每天减钱 先注释掉
        # queryset = my_models.ReduceMoneyEveryDay.objects.filter(user_id=user.id)
        # money = 0
        # if queryset.exists():
        #     reduce_instance = queryset.order_by("-id")[0]
        #     money = reduce_instance.money
        #     reduce_date = reduce_instance.reduce_date
        #     reduce_active = 1  # 已报名
        #
        #     today = datetime.date.today()
        #     if today == reduce_date:
        #         reduce_active = 3  # 今天已经参加过了 使用过了
        #
        #     if not is_workday(today):
        #         reduce_active = 2  # 节假日
        #
        # for free in level_free:
        #     if free in [i.get("c_type") for i in coupon_queryset]:
        #         default = free
        #
        # if not default:
        #     # 一元兑换券
        #     # 商品价格减去 优惠价格 = 需要支付价格
        #     if price - money > 100:
        #         for exchange in level_exchange:
        #             if exchange in [i.get("c_type") for i in coupon_queryset]:
        #                 default = exchange
        #     else:
        #         default = -1
        #
        # if not default:
        #     for reduction in level_reduction:
        #         if reduction in [i.get("c_type") for i in coupon_queryset]:
        #             default = reduction
        # money 用来判断此用户是否参加每天减一毛的活动，如果是0就没参加，因为用户只要一报名就记录上减一毛(前一天),
        # 这样当前用户第一次购买的时候就能减1毛了， 12月10号参加的报名，数据库记录12月9号减1毛了，然后直接取到最后一次减的一毛，
        # 也就是说12月10号支付直接减去这一毛

        data = {"default": default, "money": money, "reduce_active": reduce_active}
        print(data, PaymentTypeViewSets)
        return Response(data)


class ReduceMoneyViewSets(viewsets.GenericViewSet, mixins.ListModelMixin):
    permission_classes = (IsAuthenticated,)
    authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)
    serializer_class = my_serializers.ReduceMoneyEveryDaySerializers

    def get_queryset(self):
        user = self.request.user
        queryset = my_models.ReduceMoneyEveryDay.objects.filter(user_id=user.id).order_by("-id")
        return queryset


# 用户卡包列表
class UserCardBagViewSets(viewsets.GenericViewSet, mixins.ListModelMixin, mixins.UpdateModelMixin):
    permission_classes = (IsAuthenticated,)
    authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)
    pagination_class = UntilPagination
    filter_class = my_filters.UserCardBagFilter
    filter_backends = (DjangoFilterBackend, filters.SearchFilter)

    def get_serializer_class(self):
        if self.action == "update":
            return my_serializers.UpdateUserCardBagSerializers  # 拆包
        else:
            return my_serializers.UserCardBagSerializers

    def get_queryset(self):
        user = self.request.user
        queryset = my_models.UserCardBag.objects.filter(user_id=user.id).order_by("-id")
        return queryset


# 转增记录，转增，领取
class UserBagRecordViewSets(viewsets.GenericViewSet, mixins.CreateModelMixin, mixins.ListModelMixin,
                            mixins.UpdateModelMixin):
    """
    转增记录，转增，领取
    create: 转增，生成转增码
    update： 领取
    list： 转增记录
    """
    permission_classes = (IsAuthenticated,)
    authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)
    lookup_field = "record_id"  # uuid 通过uuid来进行转增
    filter_backends = (DjangoFilterBackend, filters.SearchFilter)
    filter_class = my_filters.CardBagRecordFilter
    pagination_class = UntilPagination

    def get_queryset(self):
        user_id = self.request.user.id
        return my_models.CardBagRecord.objects.filter(Q(own_user=user_id) | Q(receive_user=user_id))

    def get_serializer_class(self):
        if self.action == "create":
            return my_serializers.UserBagRecordCreateSerializers  # 转增
        elif self.action == "update":
            return my_serializers.UserBagRecordUpdateSerializers  # 领取
        else:
            return my_serializers.UserBagRecordSerializers  # 列表

    def perform_create(self, serializer):
        return serializer.save()

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        record_instance = self.perform_create(serializer)
        record_id = record_instance.record_id  # uuid 通过uuid 来生小程序码，然后进行装增
        page = serializer.validated_data["page"]
        type_source = serializer.validated_data["type_source"]
        if type_source == "wchatMini":
            from core.wchat.mini_base import wechat_client
            response = wechat_client.wxa.get_wxa_code_unlimited(record_id, page=page)
            content = b"data:image/png;base64," + base64.b64encode(response.content)
        else:
            # 普通二维码
            from core.tools.edit_photo import EditPicture
            url = page + "?scene=" + record_id
            image_stream, buf = EditPicture.make_qr_code(url)

            # 关注二维码
            # from core.wchat.wx_base import WxBase
            # wx_base = WxBase()
            # content = json.dumps({"IMCoffee": key})
            # image_stream = wx_base.get_qr_response(content, short=False)
            content = b"data:image/png;base64," + base64.b64encode(image_stream)
        return Response({"image": content}, status=status.HTTP_201_CREATED)

    def update(self, request, *args, **kwargs):
        partial = kwargs.pop('partial', False)
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        serializer.is_valid(raise_exception=True)
        self.perform_update(serializer)

        if getattr(instance, '_prefetched_objects_cache', None):
            # If 'prefetch_related' has been applied to a queryset, we need to
            # forcibly invalidate the prefetch cache on the instance.
            instance._prefetched_objects_cache = {}
        card_bag = instance.card_bag
        data = my_serializers.CardBagSerializers(card_bag, many=False, fields=("card_type", "price", "name")).data
        print(data, "UserBagRecordViewSets")

        return Response(serializer.data)


class V2UserBagRecordViewSets(viewsets.GenericViewSet, mixins.CreateModelMixin, mixins.ListModelMixin,
                              mixins.UpdateModelMixin):
    """
    转增记录，转增，领取
    create: 转增，生成转增码
    update： 领取
    list： 转增记录
    """
    permission_classes = (IsAuthenticated,)
    authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)
    lookup_field = "record_id"  # uuid 通过uuid来进行转增
    filter_backends = (DjangoFilterBackend, filters.SearchFilter)
    filter_class = my_filters.CardBagRecordFilter
    pagination_class = UntilPagination

    def get_queryset(self):
        user_id = self.request.user.id
        return my_models.CardBagRecord.objects.filter(Q(own_user=user_id) | Q(receive_user=user_id))

    def get_serializer_class(self):
        if self.action == "create":
            return my_serializers.UserBagRecordCreateSerializers  # 转增
        elif self.action == "update":
            return my_serializers.UserBagRecordUpdateSerializers  # 领取
        else:
            return my_serializers.UserBagRecordSerializers  # 列表

    def perform_create(self, serializer):
        return serializer.save()

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        record_instance = self.perform_create(serializer)
        record_id = record_instance.record_id  # uuid 通过uuid 来生小程序码，然后进行装增
        page = serializer.validated_data["page"]
        type_source = serializer.validated_data["type_source"]
        if type_source == "wchatMini":
            from core.wchat.mini_base import wechat_client_howhow
            response = wechat_client_howhow.wxa.get_wxa_code_unlimited(record_id, page=page)
            content = b"data:image/png;base64," + base64.b64encode(response.content)
        else:
            # 普通二维码
            from core.tools.edit_photo import EditPicture
            url = page + "?scene=" + record_id
            image_stream, buf = EditPicture.make_qr_code(url)

            # 关注二维码
            # from core.wchat.wx_base import WxBase
            # wx_base = WxBase()
            # content = json.dumps({"IMCoffee": key})
            # image_stream = wx_base.get_qr_response(content, short=False)
            content = b"data:image/png;base64," + base64.b64encode(image_stream)
        return Response({"image": content}, status=status.HTTP_201_CREATED)

    def update(self, request, *args, **kwargs):
        partial = kwargs.pop('partial', False)
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        serializer.is_valid(raise_exception=True)
        self.perform_update(serializer)

        if getattr(instance, '_prefetched_objects_cache', None):
            # If 'prefetch_related' has been applied to a queryset, we need to
            # forcibly invalidate the prefetch cache on the instance.
            instance._prefetched_objects_cache = {}
        card_bag = instance.card_bag
        data = my_serializers.CardBagSerializers(card_bag, many=False, fields=("card_type", "price", "name")).data
        print(data, "UserBagRecordViewSets")

        return Response(serializer.data)


class UserFoldCardBagViewSets(mixins.ListModelMixin, viewsets.GenericViewSet):
    permission_classes = (IsAuthenticated,)
    authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)
    filter_class = my_filters.UserCardFoldBagFilter
    filter_backends = (DjangoFilterBackend, filters.SearchFilter)

    def get_queryset(self):
        user_id = self.request.user.id
        # queryset = my_models.UserCardBag.objects.filter(user_id=user_id)
        # return my_models.UserCardBag.objects.group_by_bag_type(queryset)
        queryset = my_models.UserCardBag.objects.filter(user_id=user_id, giving=False, bag_status=1)
        return queryset

    def list(self, request, *args, **kwargs):
        # user_id = self.request.user.id
        # queryset = my_models.UserCardBag.objects.filter(user_id=user_id, giving=False, bag_status=1)
        queryset = self.filter_queryset(self.get_queryset())
        group_by_queryset = my_models.UserCardBag.objects.group_by_bag_type(queryset)
        card_type1 = queryset.filter(cardbag__card_type=1).order_by("-expire_day")
        card_type1_id = ""
        card_type2_id = ""
        if card_type1.exists():
            card_type1_id = card_type1.first().id
        card_type2 = queryset.filter(cardbag__card_type=2).order_by("-expire_day")
        if card_type2.exists():
            card_type2_id = card_type2.first().id
        queryset_json = []
        for i in group_by_queryset:
            data = dict()
            data["c_type"] = i.get("cardbag__card_type")
            data["price"] = "%.2f" % (i.get("cardbag__price") / 100.0)
            data["counts"] = i.get("counts")
            data["expire_day"] = i.get("expire_day").strftime("%Y-%m-%d")
            queryset_json.append(data)
        result = {"data_list": queryset_json, "card_type1_id": card_type1_id, "card_type2_id": card_type2_id}
        return Response(result)


class GroupQrCodeViewSets(mixins.ListModelMixin, viewsets.GenericViewSet):
    def get_queryset(self):
        queryset = my_models.GroupQrCode.objects.filter(show=True)
        return queryset

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        urls = [i.url for i in queryset]
        url = random.choice(urls) if urls else ""
        return HttpResponse(url)


class MobileGetViewSets(mixins.CreateModelMixin, viewsets.GenericViewSet):
    serializer_class = my_serializers.MobileGetCouponSerializers

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        h5_active_info = self.perform_create(serializer)
        # headers = self.get_success_headers(serializer.data)
        c_name = h5_active_info.c_name
        num = h5_active_info.num
        data = {"num": num, "c_name": c_name}
        return Response(data, status=status.HTTP_201_CREATED)

    def perform_create(self, serializer):
        return serializer.save()


class H5ActiveViewSets(mixins.RetrieveModelMixin, viewsets.GenericViewSet):
    lookup_field = "key"
    serializer_class = my_serializers.H5ActiveSerializers
    queryset = my_models.MakeH5.objects.filter(show=True)


class ShopInfoViewSets(mixins.ListModelMixin, viewsets.GenericViewSet):
    filter_class = my_filters.ShopInfoFilter
    filter_backends = (DjangoFilterBackend, filters.SearchFilter)
    queryset = my_models.ShopInfo.objects.all()
    serializer_class = my_serializers.ShopSerializers


class InvoiceViewSets(mixins.CreateModelMixin, viewsets.GenericViewSet, mixins.ListModelMixin):
    permission_classes = (IsAuthenticated, IsOwner)
    authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)
    serializer_class = my_serializers.InvoiceSerializers
    pagination_class = UntilPagination

    def get_queryset(self):
        return my_models.InvoiceRecord.objects.filter(username=self.request.user.username)

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        return Response(status=status.HTTP_201_CREATED)


class InvoiceInfoViewSets(viewsets.ModelViewSet):
    permission_classes = (IsAuthenticated, IsOwner)
    authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)
    lookup_field = "pk"
    serializer_class = my_serializers.InvoiceInfoSerializers

    def get_queryset(self):
        return my_models.InvoiceInfo.objects.filter(
            username=self.request.user.username
        )


# 售货员生成免费券ABC的小程序码
class MakeFreeCouponViewSets(mixins.CreateModelMixin, viewsets.GenericViewSet):
    serializer_class = my_serializers.MakeFreeCouponSerializers
    permission_classes = (IsAuthenticated,)
    authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)

    def perform_create(self, serializer):
        return serializer.save()

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        key = self.perform_create(serializer)
        from core.wchat.mini_base import wechat_client_howhow
        page = self.request.data.get("page")
        response = wechat_client_howhow.wxa.get_wxa_code_unlimited(key, page=page)
        return Response(response.content, status=status.HTTP_201_CREATED, headers=response.content)


# 领取售货员生成免费券ABC的小程序码
class ReceiveFreeCouponViewSets(mixins.CreateModelMixin, viewsets.GenericViewSet):
    permission_classes = (IsAuthenticated,)
    authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)
    serializer_class = my_serializers.ReceiveFreeCouponSerializers


# 生成群聊码
class GroupClientViewSets(mixins.ListModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet):
    serializer_class = my_serializers.GroupQRcodeCoffeeClientSerializers
    queryset = my_models.CoffeeClient.objects.filter(status=True)
    pagination_class = UntilPagination
    filter_backends = (DjangoFilterBackend, filters.SearchFilter)
    filter_class = my_filters.GroupQRCodeClientFilter
    permission_classes = (IsAuthenticated,)
    authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)

    # from core.tools.func_utils import geodistance
    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        lon = request.query_params.get("lon")
        lat = request.query_params.get("lat")
        if lon and lat and lon != "undefined" and lat != "undefined":
            serializer = self.get_serializer(queryset, many=True)
            data = distance_sorted_v2(serializer.data, lon, lat)
            return Response(data)
        else:
            return Response([])


class CitiesViewSets(mixins.ListModelMixin, viewsets.GenericViewSet):
    permission_classes = (IsAuthenticated,)
    authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)
    queryset = my_models.CoffeeClient.objects.values_list('city').distinct()

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        return Response(queryset)


# 用户会员中心
class MemberViewSets(mixins.ListModelMixin, viewsets.GenericViewSet):
    permission_classes = (IsAuthenticated,)
    authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)
    serializer_class = my_serializers.MemberListSerializers

    def get_queryset(self):
        user = self.request.user
        queryset = my_models.MemberCenter.objects.filter(user_id=user.id)
        return queryset

    def list(self, request, *args, **kwargs):
        base_queryset = self.filter_queryset(self.get_queryset())
        queryset = base_queryset.filter(finished=True)
        icon = ""
        if queryset.exists():
            instance = queryset.order_by("level").first()
            level = instance.level
            queryset = self.get_serializer(queryset, many=True).data
            icon_instance = my_models.MemberAddr.objects.filter(level=level).first()
            if icon_instance:
                icon = icon_instance.icon
        elif base_queryset.exists():
            level = 0
        else:
            level = -1
        results = {"member_list": queryset, "level": level, "icon": icon}
        return Response(results)


# 扫码领会员
class ObtainDiscountViewSets(mixins.CreateModelMixin, viewsets.GenericViewSet):
    permission_classes = (IsAuthenticated,)
    authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)
    serializer_class = my_serializers.MemberSerializers

    def get_permissions(self):
        """
        Instantiates and returns the list of permissions that this view requires.
        """
        if self.request.data.get("method") == 2:
            return [permission() for permission in self.permission_classes]
        else:
            return [rest_framework.permissions.AllowAny()]

    def get_authenticators(self):
        print(self.request.POST, 1111)
        print(self.request.body, 2222)
        body = self.request.body.decode()
        from urllib.parse import parse_qsl
        params = dict(parse_qsl(body))
        if not params:
            params = json.loads(self.request.body)
        print(params, "request data")
        if self.request.POST.get("method") in ["2", 2] or params.get("method") in ["2", 2]:
            return [auth() for auth in self.authentication_classes]
        else:
            #return [#rest_framework.authentication.BasicAuthentication(),
            #        rest_framework.authentication.SessionAuthentication()
            #        ]
            return []

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        instance = self.perform_create(serializer)
        url = instance.url
        headers = {"url": url, "level": instance.level}
        print(headers, instance.status, "sao ma shu ju")
        if instance.status is None:
            return Response(headers, status=status.HTTP_201_CREATED, headers=headers)
        else:
            if instance.status == 1:
                msg = "已经领取过了"
            else:
                msg = "等待开通"
            data = {"status": instance.status, "msg": msg, "level": instance.level}
            return Response(data, status=status.HTTP_400_BAD_REQUEST, headers=data)

    def perform_create(self, serializer):
        return serializer.save()


# 舍弃了 不用了先
class ShowObtainDiscountViewSets(mixins.CreateModelMixin, viewsets.GenericViewSet):
    serializer_class = my_serializers.ShowMemberSerializers

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        instance = self.perform_create(serializer)
        url = instance.url
        headers = {"url": url, "level": instance.level}
        print(headers, "xian shi sao ma shu ju")
        return Response(headers, status=status.HTTP_201_CREATED, headers=headers)

    def perform_create(self, serializer):
        return serializer.save()


# 好友分享
class FriendShareViewSets(mixins.CreateModelMixin, viewsets.GenericViewSet, mixins.ListModelMixin):
    permission_classes = (IsAuthenticated,)
    authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)
    def get_serializer_class(self):
        if self.action == "list":
            return my_serializers.ShareFriendRecordSerializers  # 邀请列表
        else:
            return my_serializers.ShareFriendSerializers  #

    def list(self, request, *args, **kwargs):
        user = self.request.user
        queryset = my_models.ShareFriend.objects.filter(share_id=user.id, status=True)
        serializer = self.get_serializer(queryset, many=True)
        nfp = queryset.count()  # 已经成功邀请人
        cfp = nfp * 3  # 已获得券
        data = {"list": serializer.data, "statistics": {"nfp": nfp, "cfp": cfp}}
        return Response(data)

# 支付优惠政策
class BankDiscountViewSets(mixins.ListModelMixin, viewsets.GenericViewSet):
    permission_classes = (IsAuthenticated, )
    authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)
    serializer_class = my_serializers.BankDiscountSerializers

    def list(self, request, *args, **kwargs):
        user_id = self.request.user.id
        queryset1 = my_models.BankDiscount.objects.filter(show=True, pay_type=1, user_id=user_id)
        queryset2 = my_models.BankDiscount.objects.filter(show=True, pay_type=2, user_id=user_id)
        serializer1 = self.get_serializer(queryset1, many=True)
        serializer2 = self.get_serializer(queryset2, many=True)
        data = {"wechat": serializer1.data, "yw":serializer2.data}
        return Response(data)


class PayTitleViewSets(mixins.ListModelMixin, viewsets.GenericViewSet):
    # serializer_class = my_serializers.PayTitleSerializers
    filter_backends = (DjangoFilterBackend, filters.SearchFilter)
    filter_class = my_filters.PayTitleFilter
    queryset = my_models.PayTitle.objects.filter(show=True)

    def list(self, request, *args, **kwargs):
        if request.query_params.get("orderNo"):
            queryset = self.filter_queryset(self.get_queryset())
        else:
            queryset = my_models.PayTitle.objects.none()
        # queryset = queryset.filter(show=True)
        data = {"wx": [], "ysf": []}
        for i in queryset:
            if i.pay_type == "wx":
                data["wx"].append(i.title)
            else:
                data["ysf"].append(i.title)
        return Response(data)
